<?php

namespace app\common\services;

class UploadServices extends BaseServices {

    public static function uploadFile($file_name, $file_path, $bucket = '')
    {
        //先判断图片是否存在
        if ( !$file_name) {
            return self::_error('参数文件不存在~~~');
        }
        if ( !$file_path) {
            return self::_error('请输入合法的图片地址~~~');
        }
        //在指定文件下按时间来存放图片
        $upload_config = \Yii::$app->params['uploads'];
        if ( !isset($upload_config[$bucket])) {
            return self::_error('指定参数错误~~~');
        }
        $temp_file = explode('.', $file_name);
        $file_type = strtolower(end($temp_file));
        $img_key = md5(file_get_contents($file_path));
        $upload_dir_path = self::getRootPath() . '/web' . $upload_config[$bucket] . '/';
        $folder_name = date('Ymd');
        $upload_dir = $upload_dir_path . $folder_name;
        if ( !file_exists($upload_dir)) {
            mkdir($upload_dir, 0777, true);
            chmod($upload_dir, 0777);
        }

        $file_full_name = $folder_name . '/' . $img_key . '.' . $file_type;

        if (is_uploaded_file($file_name)) {
            move_uploaded_file($file_name, $upload_dir_path . $file_full_name);
        } else {
            file_put_contents($upload_dir_path . $file_full_name, file_get_contents($file_path));
        }

        return [
            'code'      => 200,
            'file_path' => $file_full_name,
        ];
    }
}
